package com.ruoyi.web.controller.system;

import java.util.Date;
import java.util.List;

import javax.validation.constraints.NotNull;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.MonitorRuleType;
import com.ruoyi.common.enums.TriggerSource;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.Device;
import com.ruoyi.system.domain.MonitorCondition;
import com.ruoyi.system.domain.MonitorRule;
import com.ruoyi.system.domain.Product;
import com.ruoyi.system.domain.ProductTelemetry;
import com.ruoyi.system.domain.ValidationGroups.Create;
import com.ruoyi.system.domain.ValidationGroups.Select;
import com.ruoyi.system.domain.ValidationGroups.Update;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.service.IDeviceService;
import com.ruoyi.system.service.IMonitorConditionService;
import com.ruoyi.system.service.IMonitorRuleService;
import com.ruoyi.system.service.IProductService;
import com.ruoyi.system.service.IProductTelemetryService;
import com.ruoyi.system.service.ISysDeptService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Slf4j
@RestController
@RequestMapping("/system/monitor/condition")
public class MonitorConditionController extends BaseController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private IMonitorConditionService monitorConditionService;

    @Autowired
    private IMonitorRuleService monitorRuleService;

    @Autowired
    private IProductService productService;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private IProductTelemetryService telemetryService;

    private AjaxResult validate(MonitorCondition monitorCondition) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", monitorCondition.getRuleId());
        MonitorRule monitorRule = monitorRuleService.retrieve(queryVo);
        Product product = null;
        Device device = null;
        Integer productId = null;
        if (monitorRule == null) {
            return AjaxResult.error("没有找到指定的监控规则");
        }
        MonitorRuleType ruleType = MonitorRuleType.valueOfCode(monitorRule.getType());
        if (ruleType.equals(MonitorRuleType.PRODUCT)) {
            productId = monitorCondition.getProductId();
            if (productId == 0) {
                return AjaxResult.error("请输入产品id");
            }
            queryVo.filters.clear();
            queryVo.filters.put("id", productId);
            product = productService.retrieve(queryVo);
            if (product == null) {
                return AjaxResult.error("没有找到指定的产品");
            }
            List<MonitorCondition> monitorConditions = monitorRule.getConditions();
            if (monitorConditions.size() > 0) {
                Integer ruleProductId = monitorConditions.get(0).getProductId();
                if (!productId.equals(ruleProductId)) {
                    return AjaxResult.error("产品规则的所有触发条件必须针对同一个产品");
                }
            }
            if (monitorCondition.getDeviceId() > 0) {
                return AjaxResult.error("产品id应该为0");
            }
        } else if (ruleType.equals(MonitorRuleType.DEVICE)) {
            if (monitorCondition.getProductId() > 0) {
                return AjaxResult.error("产品id应该为0");
            }
            Integer deviceId = monitorCondition.getDeviceId();
            if (deviceId == 0) {
                return AjaxResult.error("请输入产品id");
            }
            queryVo.filters.clear();
            queryVo.filters.put("id", deviceId);
            device = deviceService.retrieve(queryVo);
            if (device == null) {
                return AjaxResult.error("没有找到指定的产品");
            }
            productId = device.getProductId();
        }
        Integer triggerSource = monitorCondition.getTriggerSource();
        if (triggerSource.equals(TriggerSource.TELEMETRY.getCode())) {
            Integer telemetryId = monitorCondition.getTelemetryId();
            if (telemetryId == null || telemetryId == 0) {
                return AjaxResult.error("请输入遥测id");
            }
            queryVo.filters.clear();
            queryVo.filters.put("id", telemetryId);
            ProductTelemetry productTelemetry = telemetryService.retrieve(queryVo);
            if (productTelemetry == null) {
                return AjaxResult.error("没有找到指定的遥测值");
            }
            if (!productTelemetry.getProductId().equals(productId)) {
                return AjaxResult.error("遥测值不属于指定产品");
            }
        }
        return null;
    }

    @PreAuthorize("@ss.hasPermi('system:monitor:rule:add')")
    @PostMapping(value = "/add", produces = "application/json;charset=UTF-8")
    @Log(title = "触发条件", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody @Validated(Create.class) MonitorCondition monitorCondition) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        String createBy = loginUser.getUsername();
        monitorCondition.setCompanyId(companyId);
        monitorCondition.setCreateBy(createBy);
        monitorCondition.setCreateTime(new Date());
        AjaxResult ret = validate(monitorCondition);
        if (ret != null) {
            return ret;
        }
        Integer id = monitorConditionService.create(monitorCondition);
        if (id != null) {
            return AjaxResult.success(monitorCondition);
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }

    @PreAuthorize("@ss.hasPermi('system:monitor:rule:list')")
    @GetMapping(value = "/list", produces = "application/json;charset=UTF-8")
    public Object index(@Validated(Select.class) MonitorCondition MonitorCondition) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("rule_id", MonitorCondition.getRuleId());
        queryVo.filters.put("trigger_source", MonitorCondition.getTriggerSource());
        startPage();
        List<MonitorCondition> MonitorConditions = monitorConditionService.index(queryVo);
        return getDataTable(MonitorConditions);
    }

    @PreAuthorize("@ss.hasPermi('system:monitor:rule:query')")
    @GetMapping(value = "/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult retrieve(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        MonitorCondition MonitorCondition = monitorConditionService.retrieve(queryVo);
        if (MonitorCondition == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        return AjaxResult.success(MonitorCondition);
    }

    @PreAuthorize("@ss.hasPermi('system:monitor:rule:edit')")
    @Log(title = "触发条件", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/edit", produces = "application/json;charset=UTF-8")
    public AjaxResult edit(@RequestBody @Validated(Update.class) MonitorCondition monitorCondition) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", monitorCondition.getId());
        MonitorCondition target = monitorConditionService.retrieve(queryVo);
        if (target == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        monitorCondition.setRuleId(target.getRuleId());
        monitorCondition.setTriggerSource(target.getTriggerSource());
        monitorCondition.setProductId(target.getProductId());
        monitorCondition.setDeviceId(target.getDeviceId());
        monitorCondition.setCompanyId(target.getCompanyId());
        AjaxResult ret = validate(monitorCondition);
        if (ret != null) {
            return ret;
        }
        if (monitorConditionService.update(monitorCondition)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }

    @PreAuthorize("@ss.hasPermi('system:monitor:rule:remove')")
    @Log(title = "触发条件", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult remove(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        // TODO: [ZY] check related modules
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        if (monitorConditionService.delete(queryVo)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }
}
